<?php
namespace yan\currency;
class Currency extends AbstractFactory{
	private $services = [];
	protected static $classMap = [
		'curl' => 'yan\currency\utils\Curl',
		'yahoo' => 'yan\currency\factory\FinanceYahoo',
		'ecb' => 'yan\currency\factory\EcbEuropa',
		'fixerio' => 'yan\currency\factory\FixerIo',
		'freeCurrencyApi' => 'yan\currency\factory\FreeCurrencyApi',
    ];

    public function __construct()
    {
        $this->services = [];
        if(is_file(__DIR__.'/.env')){
        	$env = parse_ini_file(__DIR__.'/.env', true);
        	foreach ($env as $key => $val) {
        		$name = strtoupper($key);
		        if (is_array($val)) {
		            foreach ($val as $k => $v) {
		                $item = $name . '_' . strtoupper($k);
		                putenv("$item=$v");
		            }
		        } else {
		            putenv("$name=$val");
		        }
        	}
        }
    }
    protected function getServiceClass($name)
    {
        return \array_key_exists($name, static::$classMap) ? static::$classMap[$name] : null;
    }
    public function __get($name)
    {
        $serviceClass = $this->getServiceClass($name);
        if (null !== $serviceClass) {
            if (!\array_key_exists($name, $this->services)) {
                if(is_array($serviceClass)){
                    if(isset($serviceClass['class'])){
                        $this->services[$name] = $serviceClass['class']::instance();
                    }
                }else{
                    $this->services[$name] = $serviceClass::instance();
                }
                
            }

            return $this->services[$name];
        }
        // \trigger_error('Undefined property: ' . static::class . '::$' . $name);
        return null;
    }

	public function run($type = 'freeCurrencyApi'){
		$service = $this->__get($type);
		return !empty($service) ? $service->run($this) : [];
		// var_dump($this->freeCurrencyApi->run($this));
	}
}